﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.Practices.EnterpriseLibrary.Security.Cryptography;
using WebStudio.Framework.Helper;

namespace WebStudio.Framework.Extension
{
    public static class StringExtension
    {

        //转换

        #region 将Base64转换成通过HTTP传递的Base64
        /// <summary>
        /// 将Base64转换成通过HTTP传递的Base64 
        /// </summary>
        /// <param name="sourceBase64"></param>
        /// <returns></returns>
        public static string Base64ToHttpBase64(this string sourceBase64)
        {
            string encodeString = sourceBase64;
            return encodeString.Replace("+", "~").Replace("/", "@").Replace("=", "$");
        }
        #endregion

        #region 将通过HTTP传递的Base64转换成Base64 
        /// <summary>
        /// 将通过HTTP传递的Base64转换成Base64
        /// </summary>
        /// <param name="sourceHttpBase64"></param>
        /// <returns></returns>
        public static string HttpBase64ToBase64(this string sourceHttpBase64)
        {
            string deocdeString = sourceHttpBase64;
            return deocdeString.Replace("~", "+").Replace("@", "/").Replace("$", "=");
        }
        #endregion
 
        #region 将IP地址转换为长整数值表示
        /// <summary>
        /// 将IP地址转换为长整数值表示 
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public static long IPConvertToLong(this string ip)
        {
            string[] items = ip.Split(new char[] { '.' });
            if (items.Length != 4)
            {
                throw new ArgumentException("IP地址非法", ip);
            }
            byte[] buffer = new byte[4];
            for (int i = 0; i < 4; i++)
            {
                buffer[i] = Convert.ToByte(items[i]);
            }
            return (long)BitConverter.ToUInt32(buffer, 0);
        }
        #endregion

        #region 普通文本转HTML函数
        /// <summary>
        /// 普通文本转HTML函数 
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string TextConvertToHTML(this string obj)
        {
            string textData = obj;
            return textData.Replace("\n", "<br>");
        }
        #endregion

        #region 普通文本转JavaScript代码函数
        /// <summary>
        /// 普通文本转JavaScript代码函数
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string TextConvertToJavaScriptScriptCode(this string obj)
        {
            string textData = obj;
            return textData.Replace(@"\", "＼").Replace("'", @"\'").Replace("\n", "<br>");
        }
        #endregion

        #region 普通文本转TooltipMessage函数
        /// <summary>
        /// 普通文本转TooltipMessage函数
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string TextConvertToTooltipMessage(this string obj)
        {
            string textData = obj;
            return textData.Replace("(", "（").Replace(")", "）").Replace(";", "；").Replace("\r\n", "<BR>").Replace("\n", "").Replace("\r", "").Replace("\"", "''").Replace("\t", "　　　　").Replace("'", "''").Replace(@"\", @"\\");
        }
        #endregion


        //文本过滤

        #region 文本提交过滤
        /// <summary>
        /// 防止恶意提交一些代码，影响系统的安全使用，通过字符转换的方法，防止这种现象的发生
        /// </summary>
        /// <param name="html">待过滤文本</param>
        /// <param name="filter">SCRIPT|TABLE|CLASS|STYLE|XML|NAMESPACE|FONT|MARQUEE|OBJECT|</param>
        /// <returns></returns>
        public static string TextSubmitFilter(this string html, string filter)
        {
            Regex r;
            Match m;
            string str = html;
            switch (filter.ToUpper())
            {
                case "SCRIPT":
                    str = Regex.Replace(str, "</?script[^>]*>", "");
                    m = new Regex("</?script[^>]*>", RegexOptions.IgnoreCase).Match(str);
                    while (m.Success)
                    {
                        str = str.Replace(m.Groups[0].ToString(), "");
                        m = m.NextMatch();
                    }
                    r = new Regex("(javascript|jscript|vbscript|vbs):", RegexOptions.IgnoreCase);
                    for (m = r.Match(str); m.Success; m = m.NextMatch())
                    {
                        str = str.Replace(m.Groups[0].ToString(), m.Groups[1].ToString() + "：");
                    }
                    r = new Regex("on(mouse|exit|error|click|key)", RegexOptions.IgnoreCase);
                    for (m = r.Match(str); m.Success; m = m.NextMatch())
                    {
                        str = str.Replace(m.Groups[0].ToString(), "<I>on" + m.Groups[1].ToString() + "</I>");
                    }
                    r = new Regex("&#", RegexOptions.IgnoreCase);
                    for (m = r.Match(str); m.Success; m = m.NextMatch())
                    {
                        str = str.Replace(m.Groups[0].ToString(), "<I>&#</I>");
                    }
                    return str;

                case "TABLE":
                    return Regex.Replace(Regex.Replace(Regex.Replace(Regex.Replace(str, "</?table[^>]*>", ""), "</?tr[^>]*>", ""), "</?th[^>]*>", ""), "</?td[^>]*>", "");

                case "CLASS":
                    r = new Regex("(<[^>]+) class=[^ |^>]*([^>]*>)", RegexOptions.IgnoreCase);
                    for (m = r.Match(str); m.Success; m = m.NextMatch())
                    {
                        str = str.Replace(m.Groups[0].ToString(), m.Groups[0].ToString() + " " + m.Groups[1].ToString());
                    }
                    return str;

                case "STYLE":
                    r = new Regex("(<[^>]+) style=\"[^\"]*\"([^>]*>)", RegexOptions.IgnoreCase);
                    for (m = r.Match(str); m.Success; m = m.NextMatch())
                    {
                        str = str.Replace(m.Groups[0].ToString(), m.Groups[0].ToString() + " " + m.Groups[1].ToString());
                    }
                    return str;

                case "XML":
                    return Regex.Replace(str, @"<\?xml[^>]*>", "");

                case "NAMESPACE":
                    return Regex.Replace(str, @"<\/?[a-z]+:[^>]*>", "");

                case "FONT":
                    return Regex.Replace(str, "</?font[^>]*>", "");

                case "MARQUEE":
                    return Regex.Replace(str, "</?marquee[^>]*>", "");

                case "OBJECT":
                    return Regex.Replace(Regex.Replace(Regex.Replace(str, "</?object[^>]*>", ""), "</?param[^>]*>", ""), "</?embed[^>]*>", "");
            }
            return str;
        }
        #endregion

        #region 过滤Like查询
        /// <summary>
        /// 过滤Like查询
        /// </summary>
        /// <param name="sqlString"></param>
        /// <returns></returns>
        public static string LikeFilter(this string sqlString)
        {
            if (sqlString == null)
            {
                return "";
            }
            sqlString = sqlString.Replace("'", "''");
            sqlString = sqlString.Replace(";", "[;]");
            sqlString = sqlString.Replace("[", "[[]");
            sqlString = sqlString.Replace("%", "[%]");
            sqlString = sqlString.Replace("_", "[_]");
            sqlString = sqlString.Replace("^", "[^]");
            sqlString = sqlString.Replace("[]", "[[]]");
            return sqlString;
        }
        #endregion

        #region SQL语句过滤
        /// <summary>
        /// SQL语句过滤
        /// </summary>
        /// <param name="sqlString"></param>
        /// <returns></returns>
        public static string SqlFilter(this string sqlString)
        {
            if (sqlString == null)
            {
                return "";
            }
            sqlString = sqlString.Replace("'", "''");
            sqlString = sqlString.Replace(";", "");
            return sqlString;
        }
        #endregion

        #region 格式化脚本函数
        /// <summary>
        /// 格式化脚本函数 
        /// </summary>
        /// <param name="pScriptBody"></param>
        /// <returns></returns>
        public static string FormateScript(this string pScriptBody)
        {
            StringBuilder strScriptBody = new StringBuilder();
            strScriptBody.Append("<Script Language=JavaScript>").Append("\r\n");
            strScriptBody.Append(pScriptBody).Append("\r\n");
            strScriptBody.Append("</Script>").Append("\r\n");
            return strScriptBody.ToString();
        }
        #endregion


        //截取文本 [过滤HTML] 

        #region 截取文本重载一
        /// <summary>
        /// 截取文本重载一
        /// </summary>
        /// <param name="textData"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string CutText(this string textData, int length)
        {
            return textData.CutText(length, false);
        }
        #endregion

        #region 截取文本重载二
        /// <summary>
        /// 截取文本重载二
        /// </summary>
        /// <param name="textData"></param>
        /// <param name="length"></param>
        /// <param name="flag"></param>
        /// <returns></returns>
        public static string CutText(this string textData, int length, bool flag)
        {
            return textData.CutText(length, flag, "...");
        }
        #endregion

        #region 截取指定长度的文本函数 [过滤HTML]
        /// <summary>
        /// 截取指定长度的文本函数 [过滤HTML] 
        /// </summary>
        /// <param name="textData"></param>
        /// <param name="length"></param>
        /// <param name="flag"></param>
        /// <param name="addString"></param>
        /// <returns></returns>
        public static string CutText(this string textData, int length, bool flag, string addString)
        {
            if (textData == null)
            {
                return "";
            }
            if (flag)
            {
                textData = Regex.Replace(textData, @"\<[^\<^\>]*\>", "");
                textData = textData.Replace("&nbsp;", "");
            }
            if (Encoding.Default.GetByteCount(textData) > length)
            {
                int i = 0;
                int j = 0;
                foreach (char Char in textData)
                {
                    if (Char > '\x007f')
                    {
                        i += 2;
                    }
                    else
                    {
                        i++;
                    }
                    if (i > length)
                    {
                        if (addString != string.Empty)
                        {
                            textData = textData.Substring(0, j) + addString;
                            return textData;
                        }
                        textData = textData.Substring(0, j);
                        return textData;
                    }
                    j++;
                }
            }
            return textData;
        }
        #endregion


        //加密

        #region 对称加密函数 [源字符串] - [结果字符串] 
        /// <summary>
        /// 对称加密函数 [源字符串] - [结果字符串] 
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static string EncryptSymmetric(this string source)
        {
            if ((source == null) || (source == ""))
            {
                return "";
            }
            try
            {
                return Cryptographer.EncryptSymmetric("DefaultProvider", source);
            }
            catch (Exception objExp)
            {
                ExceptionHelper.Handle(objExp);
                return "";
            }
        }
        #endregion

        #region 对称解密函数 [源字符串] - [结果字符串] 
        /// <summary>
        /// 对称解密函数 [源字符串] - [结果字符串] 
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static string DecryptSymmetric(this string source)
        {
            if ((source == null) || (source == ""))
            {
                    return "";
            }
            try
            {
                return Cryptographer.DecryptSymmetric("DefaultProvider", source);
            }
            catch (Exception objExp)
            {
                ExceptionHelper.Handle(objExp);
                return null;
            }
        }
        #endregion
    }
}
